package servlets;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.SortedSet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Reader;

/**
 * Servlet implementation class ReadServlet.
 */
public class ReadServlet extends HttpServlet {
    /** Serial version UID. */
    private static final long serialVersionUID = 1L;

    /**
     * Initializes the servlet.
     *
     * @param config  configuration data of the servlet
     * @throws ServletException  if there is any problem
     */
    @Override
    public void init(final ServletConfig config) throws ServletException {
        super.init(config);
    }

    /**
     * Decide if the text of a message must be shown to the reader or if the
     * message must be deleted (in which case it is deleted).
     *
     * Return the view for reading messages.
     *
     * @param request  HTTP request
     * @param response  HTTP response
     * @throws ServletException  if there is any problem
     * @throws IOException  if there is any problem
     * @see HttpServlet#doGet(HttpServletRequest request,
     *                           HttpServletResponse response)
     */
    @Override
    @SuppressWarnings("unchecked")
    protected void doGet(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        Reader reader = (Reader) request.getSession().getAttribute("reader");
        LinkedHashMap<String, Boolean> msgIDShowMap
                = (LinkedHashMap<String, Boolean>)
                        request.getSession().getAttribute("msgIDShowMap");
        LinkedHashMap<String, String> msgIDHeaderMap
                = (LinkedHashMap<String, String>)
                        request.getSession().getAttribute("msgIDHeaderMap");
        LinkedHashMap<String, String> msgIDTextMap
                = (LinkedHashMap<String, String>)
                        request.getSession().getAttribute("msgIDTextMap");
        String msgID = request.getParameter("msgID");
        if (request.getParameter("readMsg") != null) { //button read
            msgIDShowMap.put(msgID, true);
        } else if (request.getParameter("hideMsg") != null) { //button hide
            msgIDShowMap.put(msgID, false);
        } else if (request.getParameter("deleteMsg") != null) { //button delete
            reader.removeMsg(msgID);
            msgIDShowMap.remove(msgID);
            msgIDHeaderMap.remove(msgID);
            msgIDTextMap.remove(msgID);
        }
        getServletContext().getRequestDispatcher(
                "/jsp/readHeaders.jsp").forward(request, response);
    }

    /**
     * Get data about messages from the reader, create the elements that are
     * needed to show them to the human reader and put them in the session
     * context.
     *
     * Return the view for reading messages.
     *
     * @param request  HTTP request
     * @param response  HTTP response
     * @throws ServletException  if there is any problem
     * @throws IOException  if there is any problem
     * @see HttpServlet#doPost(HttpServletRequest request,
     *                            HttpServletResponse response)
     */
    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        Reader reader = (Reader) request.getSession().getAttribute("reader");
        //message IDs mapped to message headers
        LinkedHashMap<String, String> msgIDHeaderMap
                = new LinkedHashMap<String, String>();
        //message IDs mapped to message texts
        LinkedHashMap<String, String> msgIDTextMap
                = new LinkedHashMap<String, String>();
        //message IDs mapped to whether the text of the message should be shown
        LinkedHashMap<String, Boolean> msgIDShowMap
                = new LinkedHashMap<String, Boolean>();

//        Set<JMSTextMessage> messageList = reader.getPendingMsgs();
//        for (JMSTextMessage msg : messageList) {
//            String msgUUID = "unknown ID";
//            String header = "without header";
//            try {
//                msgUUID = msg.getJMSMessageID();
//                header = msg.getStringProperty("header");
//                msgIDHeaderMap.put(msgUUID, header);
//                msgIDTextMap.put(msgUUID, msg.getText());
//                msgIDShowMap.put(msgUUID, false);
//            } catch (JMSException e) {
//                System.err.println("Error getting data of message");
//            }
//        }

        SortedSet<String> messageList = reader.getPendingMsgsInfo();
        for (String msgInfo : messageList) {
            String [] data = msgInfo.split(";");
            String msgUUID = "unknown ID";
            String text = "";
            String header = "without header";
            try {
                msgUUID = data[1];
                text = data[2];
                header = data[3];
            } catch (Exception e) {
                //unexpected format of message, message without header probably
            }
            msgIDHeaderMap.put(msgUUID, header);
            msgIDTextMap.put(msgUUID, text);
            msgIDShowMap.put(msgUUID, false);
        }

        request.getSession().setAttribute("msgIDHeaderMap", msgIDHeaderMap);
        request.getSession().setAttribute("msgIDTextMap", msgIDTextMap);
        request.getSession().setAttribute("msgIDShowMap", msgIDShowMap);
        getServletContext().getRequestDispatcher(
                "/jsp/readHeaders.jsp").forward(request, response);
    }

}
